<template>
  <el-container>
    <el-header>
      <h2>调查问卷</h2>
    </el-header>
    <el-main class="centered-main">
      <el-form ref="surveyForm" :model="form" label-width="0px">
        <div v-for="(question, index) in questions" :key="index">
          <div class="question-title">
            {{ index + 1 }}. {{ question.题目标题 }}
          </div>
          <div v-if="question.类型 === '单选'">
            <el-radio-group v-model="form[question.id]">
              <el-radio
                v-for="(option, key) in questionOptions(question)"
                :key="key"
                :label="key"
              >
                {{ key }}. {{ option }}
              </el-radio>
            </el-radio-group>
          </div>
          <div v-else-if="question.类型 === '多选'">
            <el-checkbox-group v-model="form[question.id]">
              <el-checkbox
                v-for="(option, key) in questionOptions(question)"
                :key="key"
                :label="key"
              >
                {{ key }}. {{ option }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </el-form>
    </el-main>
    <el-footer>
      <el-button type="primary" @click="submitSurvey">提交问卷</el-button>
    </el-footer>
  </el-container>
</template>

<script setup lang="ts">
import { useURLStoreHook } from "@/store/modules/proxy";
import { type PaginationProps } from "@pureadmin/table";
import { message } from "@/utils/message";
import { ref, onMounted, reactive, toRaw } from "vue";
import { getDataWenJuan, saveWJDTDatas } from "@/api/dataList";
const form = ref({});
const questionOptions = question => {
  const options = {};
  ["A", "B", "C", "D", "E"].forEach(key => {
    if (question[key]) {
      options[key] = question[key];
    }
  });
  return options;
};

const submitSurvey = async () => {
  let submittedAnswers = "";
  for (const [questionId, answer] of Object.entries(form.value)) {
    // const questionIndex = questions.value.findIndex(
    //   q => q.id === parseInt(questionId)
    // );
    const questionIndex = parseInt(questionId);
    if (questionIndex !== -1) {
      const questionNumber = questionIndex;
      if (Array.isArray(answer) && answer.length > 0) {
        // 多选题处理
        submittedAnswers += `${questionNumber}-${answer.join("")}`;
      } else if (answer) {
        // 单选题处理
        submittedAnswers += `${questionNumber}-${answer}`;
      }
    }
  }
  const s = submittedAnswers.replace(/(?<=\D)(?=\d)/g, "$");
  const formanswer = reactive({
    id: useURL.id,
    tkTableName: "问卷题库",
    sjTableName: "问卷数据表",
    answer: s
  });
  const result = await saveWJDTDatas(formanswer);
  if (result.isSuccess) {
    message("提交成功！", { type: "success" });
  }
};
const pagination = reactive<PaginationProps>({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  background: true
});
const formdatas = reactive({
  // 左侧部门树的id
  deptId: 0,
  appName: "",
  isShow: "",
  onePage: pagination,
  sortName: "id",
  sort: false,
  filterArr: [],
  searchKey: "",
  editTable: "",
  selName: "wjId",
  selValue: "1"
});
const questions = ref([]);
const allids = ref([]);
const useURL = useURLStoreHook();
onMounted(async () => {
  try {
    formdatas.deptId = 166; // useURL.deptId;
    formdatas.tableName = useURL.tableName;
    formdatas.appName = "问卷题库"; //useURL.tableName;
    formdatas.selValue = useURL.id;
    const response = await getDataWenJuan(toRaw(formdatas));
    if (response.isSuccess) {
      questions.value = JSON.parse(response.data);
      allids.value = questions.value.id;
      console.log("allids" + JSON.stringify(questions.value));
    }
  } catch (error) {
    console.error("加载问卷数据失败:", error);
  }
});
</script>

<style scoped>
.el-container {
  margin: 20px;
}

.el-header {
  text-align: center;
}

.el-main.centered-main {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.question-title {
  margin-bottom: 10px;
  font-weight: bold;
}

.el-radio-group .el-checkbox-group {
  display: flex;
  flex-direction: column;
}

.el-radio,
.el-checkbox {
  display: flex;
}

.el-radio .el-checkbox {
  margin-right: 10px;
}

.el-footer {
  margin-top: 20px;
  text-align: center;
}
</style>
